import {defineStore} from "pinia";
import {reactive} from "vue";
import type {AdminLoginForm, AdminLoginRespDataInfo, AdminLoginRespInfo} from "@/type/admin.ts";
import {reqAdminLogin, reqAdminLogout} from "@/api/admin";

export const useAdminStore = defineStore('admin', () => {
    const adminInfo = reactive<AdminLoginRespDataInfo>({
        adminId: Number(localStorage.getItem('admin_id')) || -1,
        username: localStorage.getItem('username'),
        adminName: localStorage.getItem('admin_name'),
        avatar: localStorage.getItem('avatar'),
        token: localStorage.getItem('admin_token')
    })
    // 登录
    async function adminLogin(data: AdminLoginForm) {
        const result:AdminLoginRespInfo = await reqAdminLogin(data)
        if (result.code == 1) {
            adminInfo.adminId = result.data.adminId
            adminInfo.username = result.data.username
            adminInfo.adminName = result.data.adminName
            adminInfo.avatar = result.data.avatar
            adminInfo.token = result.data.token
            localStorage.setItem('admin_id',result.data.adminId.toString())
            localStorage.setItem('username',(result.data.username as string))
            localStorage.setItem('admin_name',(result.data.adminName as string))
            localStorage.setItem('avatar',(result.data.avatar as string))
            localStorage.setItem('admin_token',(result.data.token as string))
            return 'ok'
        } else {
            return Promise.reject(new Error(result.massage))
        }
    }

    // 登出
    async function adminLogout() {
        const result = await reqAdminLogout()
        if (result.code == 1) {
            adminInfo.adminId = -1
            adminInfo.username = ''
            adminInfo.adminName = ''
            adminInfo.avatar = ''
            adminInfo.token = ''
            localStorage.removeItem('admin_id')
            localStorage.removeItem('username')
            localStorage.removeItem('admin_name')
            localStorage.removeItem('avatar')
            localStorage.removeItem('admin_token')
            return 'ok'
        } else {
            return Promise.reject(new Error(result.code.toString()))
        }
    }

    return {adminInfo, adminLogin, adminLogout}
})